package com.geiliwang.web.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import redis.clients.jedis.JedisPoolConfig;

@Configuration
public class RedisConfiguration {

    @Bean
    public RedisConnectionFactory jedisConnectionFactory(@Qualifier("jedis.pool.config") JedisPoolConfig config,
                                                         @Value("${jedis.pool.host}") String host,
                                                         @Value("${jedis.pool.port}") int port,
                                                         @Value("${jedis.pool.timeout}") int timeout,
                                                         @Value("${jedis.pool.password}") String password) {

        JedisConnectionFactory jedisConnectionFactory = new JedisConnectionFactory();
        jedisConnectionFactory.setHostName(host);
        jedisConnectionFactory.setPort(port);
        jedisConnectionFactory.setTimeout(timeout);
        jedisConnectionFactory.setPassword(password);
        jedisConnectionFactory.setPoolConfig(config);
        return jedisConnectionFactory;
    }

    @Bean
    public RedisCacheTransfer redisCacheTransfer(JedisConnectionFactory jedisConnectionFactory) {
        RedisCacheTransfer redisCacheTransfer = new RedisCacheTransfer();
        redisCacheTransfer.setJedisConnectionFactory(jedisConnectionFactory);
        return redisCacheTransfer;
    }

    @Bean(name = "jedis.pool.config")
    public JedisPoolConfig jedisPoolConfig(@Value("${jedis.pool.config.maxTotal}") int maxTotal, @Value("${jedis.pool.config.maxIdle}") int maxIdle, @Value("${jedis.pool.config.maxWaitMillis}") int maxWaitMillis) {
        JedisPoolConfig config = new JedisPoolConfig();
        config.setMaxTotal(maxTotal);
        config.setMaxIdle(maxIdle);
        config.setMaxWaitMillis(maxWaitMillis);
        return config;
    }

}
